/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javalens.datageneration;

import javalens.util.UserErrorException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author vermaak
 */
public class DataSet {

    private String[] headers;
    private List<double[]> rows;

    public DataSet() {
        rows = new ArrayList<double[]>();
    }

    /** Set the headers, and may as well take a copy as there is no
     * performance hit for that
     * 
     * @param headers An array of descriptive strings
     */
    public void setHeaders(String[] headers) {
        this.headers = Arrays.copyOf(headers, headers.length);
    }

    /** Assume no copy, for performance's sake
     * 
     * @param newRow The row to add
     */
    public void addRow(double[] newRow) throws UserErrorException {
        if (rows.size() > 0 && newRow.length != rows.get(0).length) {
            throw new UserErrorException("Adding row of incorrect length");
        }
        rows.add(newRow);
    }

    public void toFile(File file) throws IOException {
        FileWriter writer = new FileWriter(file);
        for (int i = 0; i < headers.length; ++i) {
            writer.write(headers[i]);
            if (i != headers.length - 1) {
                writer.write(",");
            }
        }
        writer.write("\n");
        for (double[] values : rows) {
            for (int i = 0; i < values.length; ++i) {
                writer.write(Double.toString(values[i]));
                if (i != values.length - 1) {
                    writer.write(",");
                }
            }
            writer.write("\n");
        }
        writer.flush();
        writer.close();
    }

    public String[] getHeaders() {
        return headers;
    }

    public List<double[]> getRows() {
        return rows;
    }
}
